package com.ycy.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ycy.upload.PwdPool;
import com.ycy.upload.UploadUtil;

public class UploadServlet extends HttpServlet{

	private final String ADMINPWD = "10101100";

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		upload.setSizeMax(-1);

		boolean finished = false;
		try {
			List<FileItem> items = upload.parseRequest(req);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext() && !finished) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String fieldName = item.getFieldName();
					String fieldValue = item.getString("UTF-8");
					if ("pwd".equals(fieldName)) {
						if (PwdPool.contain(fieldValue) || ADMINPWD.equalsIgnoreCase(fieldValue)) {
							Iterator<FileItem> iterFile = items.iterator();
							while (iterFile.hasNext() && !finished) {
								FileItem itemFile = (FileItem) iterFile.next();
								if (!itemFile.isFormField() && "file".equals(itemFile.getFieldName())) {
									String fileName = itemFile.getName();
									File uploadedFile = new File(UploadUtil.getFilePath() + "/" + fileName);
									itemFile.write(uploadedFile);
									PwdPool.remove(fieldValue);
									finished = true;
								}
							}
						} else {
							resp.getWriter().print("wrong pwd.");
						}

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		resp.getWriter().print("upload finished");
	}
}
